package com.tree.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tree.backend.entity.dto.budgetConfig.BudgetConfigDTO;
import com.tree.backend.entity.dto.budgetConfig.BudgetConfigQueryDTO;
import com.tree.backend.entity.pojo.BudgetConfig;
import com.tree.backend.entity.pojo.User;
import com.tree.backend.entity.vo.budgetConfig.BudgetAnalysisItemVO;
import com.tree.backend.entity.vo.budgetConfig.BudgetAnalysisVO;
import com.tree.backend.entity.vo.budgetConfig.BudgetConfigVO;
import com.tree.backend.mapper.BudgetConfigMapper;
import com.tree.backend.service.IBudgetConfigService;
import com.tree.backend.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 部门预算配置表 服务实现类
 * </p>
 */
@Service
@RequiredArgsConstructor
public class BudgetConfigServiceImpl extends ServiceImpl<BudgetConfigMapper, BudgetConfig> implements IBudgetConfigService {

    private final DepartmentServiceImpl departmentService;
    private final CostItemServiceImpl costItemService;
    private final UserServiceImpl userService;

    @Override
    public IPage<BudgetConfigVO> getBudgetConfigs(BudgetConfigQueryDTO queryDTO) {
        // 创建分页对象
        Page<BudgetConfig> page = new Page<>(queryDTO.getPage(), queryDTO.getPageSize());
        
        // 创建查询条件
        QueryWrapper<BudgetConfig> queryWrapper = new QueryWrapper<>();
        if (queryDTO.getDepartmentId() != null) {
            queryWrapper.eq("department_id", queryDTO.getDepartmentId());
        }
        if (queryDTO.getCostItemId() != null) {
            queryWrapper.eq("cost_item_id", queryDTO.getCostItemId());
        }
        if (queryDTO.getYear() != null) {
            queryWrapper.eq("budget_year", queryDTO.getYear());
        }
        
        // 查询数据
        IPage<BudgetConfig> budgetConfigPage = baseMapper.selectPage(page, queryWrapper);
        
        // 转换为VO
        IPage<BudgetConfigVO> voPage = new Page<>(queryDTO.getPage(), queryDTO.getPageSize(), budgetConfigPage.getTotal());
        List<BudgetConfigVO> voList = new ArrayList<>();
        
        for (BudgetConfig budgetConfig : budgetConfigPage.getRecords()) {
            BudgetConfigVO vo = new BudgetConfigVO();
            vo.setId(budgetConfig.getId());
            vo.setDepartmentName(departmentService.getById(budgetConfig.getDepartmentId()).getDeptName());
            vo.setCostItemName(costItemService.getById(budgetConfig.getCostItemId()).getItemName());
            vo.setYear(budgetConfig.getBudgetYear());
            vo.setBudgetAmount(budgetConfig.getBudgetAmount());
            // 备注可以直接从实体获取
            vo.setRemark("备注信息");
            voList.add(vo);
        }
        
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public BudgetConfigVO getBudgetConfigById(Long id) {
        BudgetConfig budgetConfig = baseMapper.selectById(id);
        if (budgetConfig == null) {
            return null;
        }
        
        BudgetConfigVO vo = new BudgetConfigVO();
        vo.setId(budgetConfig.getId());
        vo.setDepartmentName(departmentService.getById(budgetConfig.getDepartmentId()).getDeptName());
        vo.setCostItemName(costItemService.getById(budgetConfig.getCostItemId()).getItemName());
        vo.setYear(budgetConfig.getBudgetYear());
        vo.setBudgetAmount(budgetConfig.getBudgetAmount());
        // 备注可以直接从实体获取
        vo.setRemark("备注信息");
        
        return vo;
    }

    @Override
    public BudgetConfigVO createBudgetConfig(BudgetConfigDTO budgetConfigDTO) {
        BudgetConfig budgetConfig = new BudgetConfig();
        budgetConfig.setDepartmentId(budgetConfigDTO.getDepartmentId());
        budgetConfig.setCostItemId(budgetConfigDTO.getCostItemId());
        budgetConfig.setBudgetYear(budgetConfigDTO.getYear());
        budgetConfig.setBudgetCycle((byte) 3); // 默认设置为年度预算
        budgetConfig.setCycleNumber((byte) 1); // 年度预算的周期序号为1
        budgetConfig.setBudgetAmount(budgetConfigDTO.getBudgetAmount());
        budgetConfig.setUsedAmount(BigDecimal.ZERO);
        budgetConfig.setRemainingAmount(budgetConfigDTO.getBudgetAmount());
        budgetConfig.setStatus((byte) 1); // 默认启用
        budgetConfig.setCreateTime(LocalDateTime.now());
        budgetConfig.setUpdateTime(LocalDateTime.now());
        
        String username = UserContext.getUsername();
        budgetConfig.setCreatorId(Long.valueOf(userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username)).getId())); // 临时设置
        baseMapper.insert(budgetConfig);
        return getBudgetConfigById(budgetConfig.getId());
    }

    @Override
    public BudgetConfigVO updateBudgetConfig(Long id, BudgetConfigDTO budgetConfigDTO) {
        BudgetConfig budgetConfig = baseMapper.selectById(id);
        if (budgetConfig == null) {
            return null;
        }
        
        budgetConfig.setDepartmentId(budgetConfigDTO.getDepartmentId());
        budgetConfig.setCostItemId(budgetConfigDTO.getCostItemId());
        budgetConfig.setBudgetYear(budgetConfigDTO.getYear());
        // 确保预算周期和周期序号有值
        if (budgetConfig.getBudgetCycle() == null) {
            budgetConfig.setBudgetCycle((byte) 3); // 默认设置为年度预算
        }
        if (budgetConfig.getCycleNumber() == null) {
            budgetConfig.setCycleNumber((byte) 1); // 年度预算的周期序号为1
        }
        budgetConfig.setBudgetAmount(budgetConfigDTO.getBudgetAmount());
        
        // 重新计算剩余金额
        budgetConfig.setRemainingAmount(budgetConfigDTO.getBudgetAmount().subtract(budgetConfig.getUsedAmount()));
        budgetConfig.setUpdateTime(LocalDateTime.now());
        
        baseMapper.updateById(budgetConfig);
        
        return getBudgetConfigById(id);
    }

    @Override
    public void deleteBudgetConfig(Long id) {
        baseMapper.deleteById(id);
    }

    @Override
    public BudgetAnalysisVO getBudgetAnalysis(Integer year) {
        BudgetAnalysisVO analysisVO = new BudgetAnalysisVO();
        
        // 实现部门预算分析数据的查询
        List<BudgetAnalysisItemVO> departmentAnalysis = new ArrayList<>();
        try {
            List<Map<String, Object>> departmentData = baseMapper.getDepartmentBudgetAnalysis(year, "");
            for (Map<String, Object> data : departmentData) {
                BudgetAnalysisItemVO item = new BudgetAnalysisItemVO();
                // 获取部门ID并查询部门名称
                if (data.get("name") != null) {
                    Long departmentId = Long.valueOf(data.get("name").toString());
                    item.setName(departmentService.getById(departmentId).getDeptName());
                }
                // 处理预算金额，确保类型正确
                getAmount(departmentAnalysis, data, item);
            }
        } catch (Exception e) {
            // 异常处理，避免因数据问题导致整个方法失败
            e.printStackTrace();
        }
        
        // 实现成本项目预算分析数据的查询
        List<BudgetAnalysisItemVO> costItemAnalysis = new ArrayList<>();
        try {
            List<Map<String, Object>> costItemData = baseMapper.getCostItemBudgetAnalysis(year, "");
            for (Map<String, Object> data : costItemData) {
                BudgetAnalysisItemVO item = new BudgetAnalysisItemVO();
                // 获取成本项目ID并查询成本项目名称
                if (data.get("name") != null) {
                    Long costItemId = Long.valueOf(data.get("name").toString());
                    item.setName(costItemService.getById(costItemId).getItemName());
                }
                // 处理预算金额，确保类型正确
                getAmount(costItemAnalysis, data, item);
            }
        } catch (Exception e) {
            // 异常处理，避免因数据问题导致整个方法失败
            e.printStackTrace();
        }
        
        analysisVO.setDepartmentAnalysis(departmentAnalysis);
        analysisVO.setCostItemAnalysis(costItemAnalysis);
        
        return analysisVO;
    }

    private void getAmount(List<BudgetAnalysisItemVO> analysisList, Map<String, Object> data, BudgetAnalysisItemVO item) {
        if (data.get("budgetAmount") != null) {
            Object budgetAmountObj = data.get("budgetAmount");
            if (budgetAmountObj instanceof BigDecimal) {
                item.setValue((BigDecimal) budgetAmountObj);
            } else if (budgetAmountObj instanceof Double) {
                item.setValue(BigDecimal.valueOf((Double) budgetAmountObj));
            } else if (budgetAmountObj instanceof Integer) {
                item.setValue(BigDecimal.valueOf((Integer) budgetAmountObj));
            } else if (budgetAmountObj instanceof Long) {
                item.setValue(BigDecimal.valueOf((Long) budgetAmountObj));
            } else {
                item.setValue(BigDecimal.ZERO);
            }
        } else {
            item.setValue(BigDecimal.ZERO);
        }
        analysisList.add(item);
    }
}
